//
//  ApplicationStream.m
//  Pennyworth Punch Clock
//
//  Created by Chris Karr on 7/16/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "ApplicationStream.h"
#import "AppDelegate.h"

#define LOG_ACTIVE_APPLICATION @"Log_Active_Application"

@implementation ApplicationStream

@synthesize timer;
@synthesize lastActive;

- (void) awakeFromNib
{
	self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update:) userInfo:nil repeats:YES];
}

- (void) update:(NSTimer *) theTimer
{
	if (![[NSUserDefaults standardUserDefaults] boolForKey:LOG_ACTIVE_APPLICATION])
		return;

	NSDictionary * active = [[NSWorkspace sharedWorkspace] activeApplication];

	NSString * appName = [active valueForKey:@"NSApplicationName"];
	
	BOOL isAgent = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"LSUIElement"] boolValue];
	BOOL isMe = [[active valueForKey:@"NSApplicationBundleIdentifier"] isEqual:[[NSBundle mainBundle] bundleIdentifier]];
	
	if ((self.lastActive == nil || ![self.lastActive isEqualToString:appName]) && 
		(!isAgent || !isMe))
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:NSLocalizedString (@"Active Application", nil) forKey:KEY];
		[note setValue:appName forKey:PREDICTION];
		
		[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
		
		self.lastActive = appName;
	}
}

@end
